package org.yfh.common.utils;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

@NoArgsConstructor(access = AccessLevel.PRIVATE)

public class EsCovertUtils {
  public static final Gson gson = new Gson();

  public static <T> T covert(SearchHit source, Class<T> tClass) {
    String esSource = source.getSourceAsString();
    return gson.fromJson(esSource, tClass);
  }

  public static <T> List<T> covert(SearchHit[] source, Class<T> tClass, String... highlightFields) {
    List<T> result = Lists.newArrayList();
    List<String> highlightFieldList = Arrays.asList(highlightFields);
    for(SearchHit searchHit : source) {
      Map<String, Object> esSourceMap = searchHit.getSourceAsMap();
      Map<String, HighlightField> highlightFieldMap = searchHit.getHighlightFields();
      if(Objects.nonNull(highlightFieldMap)) {
        highlightFieldMap.forEach((k, v) -> {
          if(CollectionUtils.isNotEmpty(highlightFieldList) && highlightFieldList.contains(k)) {
            esSourceMap.put(k, v.fragments()[0].string());
          }
        });
      }
      result.add(gson.fromJson(gson.toJson(esSourceMap), tClass));
    }
    return result;
  }
}
